﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using YQGL.Common;

namespace YQGL.Controllers
{
    public class IndexController : Controller
    {
        BLL.DL_QY DL_QYBll = new BLL.DL_QY();
        BLL.DJ_QYZCXX DJ_QYZCXXBLL = new BLL.DJ_QYZCXX();
        BLL.TblUser TblUserBLL = new BLL.TblUser();
        //
        // GET: /Index/

        public ActionResult Index()
        {
            OperateSession.add("isLogin", "N");
            return View("Index");
        }


        public ActionResult GetValidateCodeImage()
        {
            //防止网页后退--禁止缓存    
            letterWidth = 20;
            letterHeight = 44;
            string str_ValidateCode = GetRandomNumberString(letterCount);

            OperateSession.add("ValidateCode", str_ValidateCode);
            //HttpCookie objCookie = new HttpCookie("ValidateCode");
            //objCookie.Value = str_ValidateCode;
            //objCookie.Path = "/";
            //objCookie.Expires = DateTime.MaxValue;
            //Response.Cookies.Add(objCookie);

            //Response.Cookies.Add(new HttpCookie("ValidateCode", str_ValidateCode));// 使用这个方法会有错误

            return File(CreateImage(str_ValidateCode), "image/Png");
        }

        public ActionResult GetValidateCodeImage1()
        {
            //防止网页后退--禁止缓存    
            letterWidth = 20;
            letterHeight = 44;
            string str_ValidateCode = GetRandomNumberString(letterCount);

            OperateSession.add("ValidateCode1", str_ValidateCode);
            //HttpCookie objCookie = new HttpCookie("ValidateCode");
            //objCookie.Value = str_ValidateCode;
            //objCookie.Path = "/";
            //objCookie.Expires = DateTime.MaxValue;
            //Response.Cookies.Add(objCookie);

            //Response.Cookies.Add(new HttpCookie("ValidateCode", str_ValidateCode));// 使用这个方法会有错误

            return File(CreateImage(str_ValidateCode), "image/Png");
        }
        public ActionResult GetValidateCodeImage3()
        {
            //防止网页后退--禁止缓存    
            letterWidth = 20;
            letterHeight = 44;
            string str_ValidateCode = GetRandomNumberString(letterCount);

            OperateSession.add("ValidateCode3", str_ValidateCode);
            //HttpCookie objCookie = new HttpCookie("ValidateCode");
            //objCookie.Value = str_ValidateCode;
            //objCookie.Path = "/";
            //objCookie.Expires = DateTime.MaxValue;
            //Response.Cookies.Add(objCookie);

            //Response.Cookies.Add(new HttpCookie("ValidateCode", str_ValidateCode));// 使用这个方法会有错误

            return File(CreateImage(str_ValidateCode), "image/Png");
        }
        /// <summary>
        /// 创建图片
        /// </summary>
        /// <param name="checkCode"></param>
        public byte[] CreateImage(string checkCode)
        {

            int int_ImageWidth = checkCode.Length * letterWidth;
            Random newRandom = new Random();
            Bitmap image = new Bitmap(int_ImageWidth, letterHeight);
            Graphics g = Graphics.FromImage(image);
            //生成随机生成器
            Random random = new Random();
            //白色背景
            g.Clear(Color.White);
            //画图片的背景噪音线
            for (int i = 0; i < 10; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);

                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }

            //画图片的前景噪音点
            for (int i = 0; i < 10; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);

                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }
            //随机字体和颜色的验证码字符

            int findex;
            for (int int_index = 0; int_index < checkCode.Length; int_index++)
            {
                findex = newRandom.Next(fonts.Length - 1);
                string str_char = checkCode.Substring(int_index, 1);
                Brush newBrush = new SolidBrush(GetRandomColor());
                Point thePos = new Point(int_index * letterWidth + 1 + newRandom.Next(3), 12 + newRandom.Next(3));
                g.DrawString(str_char, new Font(fonts[findex], 12, FontStyle.Bold), newBrush, thePos);
            }
            //灰色边框
            g.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, (letterHeight - 1));
            //图片扭曲
            image = TwistImage(image, true, 1, 4);
            //将生成的图片发回客户端
            MemoryStream ms = new MemoryStream();
            image.Save(ms, ImageFormat.Png);
            //Response.ClearContent(); //需要输出图象信息 要修改HTTP头 
            //Response.ContentType = "image/Png";
            //Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            image.Dispose();
            return ms.ToArray();
        }
        /// <summary>
        /// 正弦曲线Wave扭曲图片
        /// </summary>
        /// <param name="srcBmp">图片路径</param>
        /// <param name="bXDir">如果扭曲则选择为True</param>
        /// <param name="nMultValue">波形的幅度倍数，越大扭曲的程度越高，一般为3</param>
        /// <param name="dPhase">波形的起始相位，取值区间[0-2*PI)</param>
        /// <returns></returns>
        public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
        {
            System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);

            // 将位图背景填充为白色
            System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);

            graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);

            graph.Dispose();

            double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;

            for (int i = 0; i < destBmp.Width; i++)
            {
                for (int j = 0; j < destBmp.Height; j++)
                {
                    double dx = 0;

                    dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;

                    dx += dPhase;

                    double dy = Math.Sin(dx);

                    // 取得当前点的颜色
                    int nOldX = 0, nOldY = 0;

                    nOldX = bXDir ? i + (int)(dy * dMultValue) : i;

                    nOldY = bXDir ? j : j + (int)(dy * dMultValue);

                    System.Drawing.Color color = srcBmp.GetPixel(i, j);
                    if (nOldX >= 0 && nOldX < destBmp.Width && nOldY >= 0 && nOldY < destBmp.Height)
                    {
                        destBmp.SetPixel(nOldX, nOldY, color);
                    }
                }
            }
            return destBmp;
        }

        private int letterWidth = 44;//单个字体的宽度范围
        private int letterHeight = 44;//单个字体的高度范围
        private int letterCount = 4;//验证码位数
        private char[] chars = "0123456789".ToCharArray();
        private string[] fonts = { "Arial", "Georgia" };
        /// <summary>
        /// 产生波形滤镜效果
        /// </summary>
        private const double PI = 3.1415926535897932384626433832795;
        private const double PI2 = 6.283185307179586476925286766559;

        public Color GetRandomColor()
        {
            Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
            System.Threading.Thread.Sleep(RandomNum_First.Next(50));
            Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);

            //  为了在白色背景上显示，尽量生成深色
            //int int_Red = RandomNum_First.Next(256);
            //int int_Green = RandomNum_Sencond.Next(256);
            //int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
            //int_Blue = (int_Blue > 255) ? 255 : int_Blue;
            int int_Red = RandomNum_First.Next(180);
            int int_Green = RandomNum_Sencond.Next(180);
            int int_Blue = (int_Red + int_Green > 300) ? 0 : 400 - int_Red - int_Green;
            int_Blue = (int_Blue > 255) ? 255 : int_Blue;
            return Color.FromArgb(int_Red, int_Green, int_Blue);
        }
        //  生成随机数字字符串
        public string GetRandomNumberString(int int_NumberLength)
        {
            Random random = new Random();
            string validateCode = string.Empty;
            for (int i = 0; i < int_NumberLength; i++)
                validateCode += chars[random.Next(0, chars.Length)].ToString();
            return validateCode;
        }

        public string ResetPWD()
        {

            var usernamePWD = Fetch.Post("usernamePWD");
            var userPhone = Fetch.Post("userPhone");
            var ValidateCode3 = Fetch.Post("ValidateCode3i");
            string DXYZM = Fetch.Post("DXYZM");
            bool isSuccess = true;
            string errorMessage = "";
            if (ValidateCode3 != OperateSession.get("ValidateCode3"))
            {
                isSuccess = false;
                errorMessage = "验证码填写错误";
            }
            if (isSuccess)
            {

                Model.DJ_QYZCXX infoModel = DJ_QYZCXXBLL.GetModel(usernamePWD.Trim());
                if (infoModel == null)
                {
                    isSuccess = false;
                    errorMessage = "企业短信号码未登记";
                }
                else
                {

                    if (infoModel.DXHM.Trim() != userPhone.Trim())
                    {
                        isSuccess = false;
                        errorMessage = "企业短信号码填写错误";
                    }
                    else
                    {

                        if (DXYZM != OperateSession.get("DXYZM"))
                        {

                            isSuccess = false;
                            errorMessage = "短信验证码填写错误";
                        }
                        else
                        {

                            OperateSession.add("LoginID", usernamePWD);
                            OperateSession.add("PWDType", "1");
                            return "重置成功";
                        }


                    }

                }
            }
            return errorMessage;

        }
        public string RegUser()
        {
            string txtUserName = Fetch.Post("r_username");
            string txtPassword = Fetch.Post("r_password");

            string txtPassword2 = Fetch.Post("r_password2");
            string ValCode = Fetch.Post("ValidateCode1");
            bool isSuccess = true;
            string errorMessage = "";

            if (ValCode.Trim() != OperateSession.get("ValidateCode1"))
            {


                isSuccess = false;
                errorMessage = "验证码填写错误";
            }
            if (txtPassword != txtPassword2)
            {


                isSuccess = false;
                errorMessage = "重复密码不一致";
            }
            Model.DL_QY userModelold = DL_QYBll.GetModel(txtUserName);
            if (userModelold != null)
            {
                isSuccess = false;
                errorMessage = "用户已存在";
            }
            if (isSuccess)
            {

                try
                {
                    Model.DL_QY userModel = new Model.DL_QY();
                    userModel.QYBM = txtUserName;
                    userModel.Pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword, "MD5");
                    userModel.LoginTime = DateTime.Now;
                    userModel.LoginIP = YQGL.Common.GenerateUtil.GetClientIPv4Address();
                    DL_QYBll.Add(userModel);

                    errorMessage = "注册成功";
                    OperateSession.add("LoginID", txtUserName);
                }
                catch (System.Exception ex)
                {
                    errorMessage = ex.Message;

                }

            }
            return errorMessage;
        }
        [HttpPost]
        public string SendPhone(string usernamePWD, string userPhone, string ValidateCode3)
        {

            bool isSuccess = true;
            string errorMessage = "";
            if (ValidateCode3 != OperateSession.get("ValidateCode3"))
            {
                isSuccess = false;
                errorMessage = "验证码填写错误";
            }
            if (isSuccess)
            {

                Model.DJ_QYZCXX infoModel = DJ_QYZCXXBLL.GetModel(usernamePWD.Trim());
                if (infoModel == null)
                {
                    isSuccess = false;
                    errorMessage = "企业短信号码未登记";
                }
                else
                {

                    if (infoModel.DXHM.Trim() != userPhone.Trim())
                    {
                        isSuccess = false;
                        errorMessage = "企业短信号码填写错误";
                    }
                    else
                    {
                        string DXYZM = GetRandomNumberString(letterCount);
                        //
                        //OperateSession.add("DXYZM", DXYZM);
                        //                    return "ok";
                        //
                        string contentStr = "【园区管理系统】您已经成功申请重置密码,验证码：" + DXYZM + ",填写完毕后进入重置修改密码页面";
                        string MSGUrl = "http://apis.baidu.com/kingtto_media/106sms/106sms?mobile=" + userPhone.Trim() + "&content=" + contentStr;
                        HttpWebRequest http = WebRequest.Create(MSGUrl) as HttpWebRequest;
                        http.Headers.Add("apikey", GlobalConstant.GLOBAL_APIKEY);
                        http.Method = "GET";
                        http.ContentType = "application/x-www-form-urlencoded";
                        http.AllowAutoRedirect = true;
                        http.KeepAlive = true;
                        http.CookieContainer = new CookieContainer();
                        using (HttpWebResponse response = http.GetResponse() as HttpWebResponse)
                        {

                            StreamReader reader = new StreamReader(response.GetResponseStream());
                            string outContent = reader.ReadToEnd();
                            if (outContent.Contains("ok"))
                            {
                                OperateSession.add("DXYZM", DXYZM);
                                return "ok";
                            }
                            else
                            {
                                return "短信验证码发发送失败";
                            }
                        }
                    }


                }
            }
            return errorMessage;
        }
        public string Login()
        {
            string txtUserName = Fetch.Post("username");
            string txtPassword = Fetch.Post("password");
            string ValCode = Fetch.Post("ValidateCode");

            bool isSuccess = true;
            string errorMessage = "";
            if (TblUserBLL.Exists(txtUserName))
            {

                if (ValCode.Trim() != OperateSession.get("ValidateCode"))
                {


                    isSuccess = false;
                    errorMessage = "验证码填写错误";
                }

                if (isSuccess)
                {
                    Model.TblUser TblUserModel = TblUserBLL.GetModel(txtUserName);

                    if (TblUserModel == null)
                    {
                        isSuccess = false;
                        errorMessage = "用户名或密码错误"; ;
                    }
                    else
                    {
                        if (TblUserModel.PWD.ToLower() != FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword, "MD5").ToLower())
                        {

                            isSuccess = false;
                            errorMessage = "用户名或密码错误"; ;
                        }
                        else
                        {

                            if (Fetch.Post("remember").ToLower().Contains("true"))
                            {
                                if (Request.Cookies["userName"] == null | Request.Cookies["passWord"] == null)
                                {
                                    Response.Cookies["rmbUser"].Value = "true";
                                    Response.Cookies["userName"].Value = txtUserName.ToString();
                                    Response.Cookies["passWord"].Value = txtPassword.ToString();
                                    Response.Cookies["userName"].Expires = DateTime.Now.AddYears(1);
                                    Response.Cookies["passWord"].Expires = DateTime.Now.AddYears(1);
                                    Response.Cookies["rmbUser"].Expires = DateTime.Now.AddYears(1);
                                }
                                else
                                {
                                    if (txtUserName == Request.Cookies["userName"].Value.ToString() & txtPassword == Request.Cookies["passWord"].Value.ToString())
                                    {

                                        Request.Cookies["userName"].Expires = DateTime.Now.AddYears(1);
                                        Request.Cookies["passWord"].Expires = DateTime.Now.AddYears(1);
                                        Request.Cookies["rmbUser"].Expires = DateTime.Now.AddYears(1);
                                    }
                                    else
                                    {
                                        Response.Cookies["rmbUser"].Value = "true";
                                        Response.Cookies["userName"].Value = txtUserName.ToString();
                                        Response.Cookies["passWord"].Value = txtPassword.ToString();
                                        Response.Cookies["userName"].Expires = DateTime.Now.AddYears(1);
                                        Response.Cookies["passWord"].Expires = DateTime.Now.AddYears(1);
                                        Response.Cookies["rmbUser"].Expires = DateTime.Now.AddYears(1);
                                    }
                                }
                            }
                            else
                            {
                                CookiesMethod.Remove("rmbUser");
                                CookiesMethod.Remove("userName");
                                CookiesMethod.Remove("passWord");




                            }

                            try
                            {
                                TblUserModel.LoginTime = DateTime.Now;
                                TblUserModel.UserIp = YQGL.Common.GenerateUtil.GetClientIPv4Address();
                                TblUserBLL.Update(TblUserModel);
                                OperateSession.add("AdminLoginID", txtUserName);
                                errorMessage = "登陆成功,欢迎进入园区段管理系统";
                            }
                            catch (System.Exception ex)
                            {
                                errorMessage = ex.Message;
                            }
                        }


                    }
                }
            }
            else
            {
                if (ValCode.Trim() != OperateSession.get("ValidateCode"))
                {


                    isSuccess = false;
                    errorMessage = "验证码填写错误";
                }

                if (isSuccess)
                {
                    Model.DL_QY userModel = DL_QYBll.GetModel(txtUserName);
                    if (userModel == null)
                    {
                        isSuccess = false;
                        errorMessage = "用户名或密码错误"; ;
                    }
                    else
                    {
                        if (userModel.Pwd.ToLower() != FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword, "MD5").ToLower())
                        {

                            isSuccess = false;
                            errorMessage = "用户名或密码错误"; ;
                        }
                        else
                        {
                            if (Fetch.Post("remember").ToLower().Contains("true"))
                            {
                                if (Request.Cookies["userName"] == null | Request.Cookies["passWord"] == null)
                                {
                                    Response.Cookies["rmbUser"].Value = "true";
                                    Response.Cookies["userName"].Value = txtUserName.ToString();
                                    Response.Cookies["passWord"].Value = txtPassword.ToString();
                                    Response.Cookies["userName"].Expires = DateTime.Now.AddYears(1);
                                    Response.Cookies["passWord"].Expires = DateTime.Now.AddYears(1);
                                    Response.Cookies["rmbUser"].Expires = DateTime.Now.AddYears(1);
                                }
                                else
                                {
                                    if (txtUserName == Request.Cookies["userName"].Value.ToString() & txtPassword == Request.Cookies["passWord"].Value.ToString())
                                    {

                                        Request.Cookies["userName"].Expires = DateTime.Now.AddYears(1);
                                        Request.Cookies["passWord"].Expires = DateTime.Now.AddYears(1);
                                        Request.Cookies["rmbUser"].Expires = DateTime.Now.AddYears(1);
                                    }
                                    else
                                    {
                                        Response.Cookies["rmbUser"].Value = "true";
                                        Response.Cookies["userName"].Value = txtUserName.ToString();
                                        Response.Cookies["passWord"].Value = txtPassword.ToString();
                                        Response.Cookies["userName"].Expires = DateTime.Now.AddYears(1);
                                        Response.Cookies["passWord"].Expires = DateTime.Now.AddYears(1);
                                        Response.Cookies["rmbUser"].Expires = DateTime.Now.AddYears(1);
                                    }
                                }
                            }
                            else
                            {
                                CookiesMethod.Remove("rmbUser");
                                CookiesMethod.Remove("userName");
                                CookiesMethod.Remove("passWord");




                            }

                            try
                            {
                                userModel.LoginTime = DateTime.Now;
                                userModel.LoginIP = YQGL.Common.GenerateUtil.GetClientIPv4Address();
                                DL_QYBll.Update(userModel);
                                OperateSession.add("LoginID", txtUserName);
                                errorMessage = "登陆成功";
                            }
                            catch (System.Exception ex)
                            {
                                errorMessage = ex.Message;
                            }
                        }

                    }
                }
            }
            return errorMessage;
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginID"></param>
        /// <param name="password"></param>
        /// <returns></returns>

    }
}
